<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="模块名称" prop="moduleName">
        <el-input
          style="width: 230px"
          v-model="queryParams.moduleName"
          placeholder="请输入自定义模块名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者来源">
        <el-cascader
          style="width: 230px"
          :props="defaultProps"
          v-model="cascaders"
          @change="querySubChange"
          clearable
          :options="deptOptions"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="模块状态">
        <el-select
          v-model="queryParams.moduleStatus"
          placeholder="请选择指导状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.visit_module_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gonitis:visit:module:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gonitis:visit:module:edit']"
          >修改</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="visitModuleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模块编号" align="center" prop="id" />
      <el-table-column
        label="模块名称"
        align="center"
        prop="moduleName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="患者来源" align="center" prop="subName" />
      <el-table-column
        label="模块备注"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="显示顺序" align="center" prop="moduleSort" />
      <el-table-column prop="createTime" align="center" width="100" label="创建时间" />
      <el-table-column prop="createName" align="center" width="100" label="创建人" />
      <el-table-column label="模块状态" align="center" prop="moduleStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.visit_module_status"
            :value="scope.row.moduleStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gonitis:visit:module:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gonitis:visit:module:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['gonitis:visit:module:detail']"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      :title="editTitle"
      :visible.sync="editVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div class="form-container">
        <el-steps
          :active="active"
          finish-status="success"
          simple
          style="margin-bottom: 40px"
        >
          <el-step title="随访模块"></el-step>
          <el-step title="模块字段"></el-step>
        </el-steps>
        <div v-show="active === 0" v-loading="step1Loading" class="step1">
          <el-form
            ref="formData1"
            :model="formData1"
            :rules="rules"
            size="medium"
            label-width="100px"
          >
            <el-form-item label="患者来源" prop="subId">
              <el-cascader
                v-model="subIds"
                style="width: 230px"
                @change="handleSubChange"
                :options="subOptions"
                :props="defaultProps"
                placeholder="请选择患者来源"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="模块名称" prop="moduleName">
              <el-input
                v-model="formData1.moduleName"
                placeholder="请输入模块名称"
                :maxlength="18"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
            <el-form-item label="显示顺序" prop="moduleSort">
              <el-input-number
                :min="0"
                :max="10"
                style="width: 230px"
                v-model="formData1.moduleSort"
                placeholder="显示顺序"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="模块备注" prop="remark">
              <el-input
                v-model="formData1.remark"
                type="textarea"
                placeholder="请输入模块备注"
                :maxlength="50"
                show-word-limit
                :autosize="{ minRows: 2, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- 字段添加表单 -->
        <div v-loading="step2Loading" v-show="active === 1" class="step2">
          <el-form
            ref="formData2"
            :model="formData2"
            :rules="rules"
            size="medium"
            label-width="100px"
          >
            <el-form-item label="字段名称" prop="fieldName">
              <el-input
                v-model="formData2.fieldName"
                placeholder="请输入模块字段名称"
                :maxlength="8"
                show-word-limit
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
            <el-form-item label="字段类型" prop="fieldType">
              <el-select
                style="width: 230px"
                v-model="formData2.fieldType"
                placeholder="请选择字段类型"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="显示顺序" prop="fieldSort">
              <el-input-number
                :min="0"
                :max="10"
                style="width: 230px"
                v-model="formData2.fieldSort"
                placeholder="字段显示顺序"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="字段备注" prop="remark">
              <el-input
                v-model="formData2.remark"
                type="textarea"
                placeholder="请输入字段备注"
                :maxlength="50"
                show-word-limit
                :autosize="{ minRows: 2, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-form>
          <!-- 添加字段 -->
          <div style="margin-left: 30px">
            <el-button
              @click="addFiledHandle"
              size="small"
              icon="el-icon-plus"
              type="success"
              plain
              >添加字段</el-button
            >
          </div>

          <!-- 字段列表 -->
          <div style="margin-top: 30px; margin-left: 30px">
            <el-tabs
              v-model="visitFieldValue"
              type="card"
              closable
              @tab-remove="removeFieldHandle"
            >
              <el-tab-pane
                v-for="(item, index) in visitFieldList"
                :key="index"
                :label="'字段' + (index + 1)"
                :name="index + ''"
              >
                <el-form
                  ref="editForm"
                  :model="visitFieldList[index]"
                  :rules="rules"
                  size="small"
                  label-width="100px"
                  v-loading="tabLoading"
                >
                  <el-form-item label="字段名称" prop="fieldName">
                    <el-input
                      v-model="visitFieldList[index].fieldName"
                      placeholder="请输入模块字段名称"
                      :maxlength="8"
                      show-word-limit
                      clearable
                      :style="{ width: '100%' }"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="字段类型" prop="fieldType">
                    <el-select
                      style="width: 230px"
                      v-model="visitFieldList[index].fieldType"
                      placeholder="请选择字段类型"
                    >
                      <el-option
                        v-for="item in typeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="显示顺序" prop="fieldSort">
                    <el-input-number
                      :min="0"
                      :max="10"
                      style="width: 230px"
                      v-model="visitFieldList[index].fieldSort"
                      placeholder="字段显示顺序"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item label="字段备注" prop="remark">
                    <el-input
                      v-model="visitFieldList[index].remark"
                      type="textarea"
                      placeholder="请输入字段备注"
                      :maxlength="50"
                      show-word-limit
                      :autosize="{ minRows: 2, maxRows: 4 }"
                      :style="{ width: '100%' }"
                    ></el-input>
                  </el-form-item>
                </el-form>
                <!-- 修改按钮 -->
                <div>
                  <el-button
                    plain
                    type="warning"
                    size="small"
                    @click="updateField"
                    icon="el-icon-edit"
                    v-if="!isSave"
                    >修改字段</el-button
                  >
                </div>
              </el-tab-pane>
              <el-divider
                v-if="visitFieldList != null && visitFieldList.length > 0"
              ></el-divider>
            </el-tabs>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="active = 0" v-if="active === 1">上一步</el-button>
        <el-button
          @click="handleSubmit()"
          :loading="buttonLoading"
          type="primary"
          v-if="active === 1 && isSave"
          >保存并退出</el-button
        >
        <el-tooltip
          class="item"
          effect="dark"
          content="修改已经保存，可以直接退出"
          placement="top"
          v-if="active === 1 && !isSave"
        >
          <el-button @click="handleClose()" type="primary">直接退出</el-button>
        </el-tooltip>
        <el-button
          v-if="active === 0"
          type="primary"
          :loading="buttonLoading"
          @click="submitForm"
          >保存并下一步</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="随访模块详情"
      :visible.sync="detailVisible"
      width="50%"
      :before-close="detailClose"
    >
      <div class="visit-detail" v-loading="detailLoading">
        <el-descriptions class="margin-top" title="随访模块信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">模块名称</template>
            {{ detailModule.moduleName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">患者来源</template>
            {{ detailModule.subName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">创建编号</template>
            {{ detailModule.createBy }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">创建人</template>
            {{ detailModule.createName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">模块备注</template>
            {{ detailModule.remark }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">创建时间</template>
            {{ detailModule.createTime }}
          </el-descriptions-item>
        </el-descriptions>
        <h3 style="color: #00000; font-weight: bold">模块字段信息</h3>
        <el-table :data="detailFileds" stripe style="width: 100%">
          <el-table-column
            prop="id"
            label="字段编号"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="fieldName"
            align="center"
            label="字段名称"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="fieldSort"
            align="center"
            label="字段顺序"
          ></el-table-column>
          <el-table-column prop="fieldType" align="center" label="字段类型">
            <template slot-scope="scope">{{
              scope.row.fieldType === 0 ? "文本" : "数字"
            }}</template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailClose">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { subTree } from "@/api/gonitis/illSub";
import {
  listVisitModule,
  saveVisitModule,
  updateVisitModule,
  saveVisitField,
  removeVisitField,
  updateVisitField,
  saveBatchField,
  infoVisitModule,
  removeVisitModule,
  detailModuleById,
} from "@/api/gonitis/visit";
export default {
  name: "VisitModule",
  dicts: ["visit_module_status"],
  data() {
    return {
      // 详情加载动画
      detailLoading: false,
      // 详情模块对象
      detailModule: {},
      // 详情字段对象
      detailFileds: [],
      // 详情可见
      detailVisible: false,
      cascaders: [],
      // 病情多选框映射
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
      },
      subIds: [],
      isSave: false,
      tabLoading: false,
      visitFieldValue: null,
      step2Loading: false,
      step1Loading: false,
      visitFieldList: [],
      typeOptions: [
        { label: "文本", value: 0 },
        { label: "数字", value: 1 },
      ],
      // 添加步骤条参数
      active: 0,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      visitModuleList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        moduleName: undefined,
        subId: undefined,
      },
      // 时间间隔
      dateRange: [],
      // 表单数据
      editVisible: false,
      editTitle: "",
      formData1: {
        id: undefined,
        subId: null,
        moduleName: "",
        moduleSort: 0,
        remark: undefined,
      },
      formData2: {
        id: undefined,
        fieldName: "",
        fieldSort: null,
        fieldType: null,
        remark: undefined,
      },
      subOptions: [],
      deptOptions: [],
      rules: {
        fieldSort: [
          {
            required: true,
            message: "请输入显示顺序",
            trigger: ["blur", "change"],
          },
        ],
        fieldName: [
          {
            required: true,
            message: "请输入字段名称",
            trigger: "blur",
          },
        ],
        fieldType: [
          {
            required: true,
            message: "请选择显示字段类型",
            trigger: ["blur", "change"],
          },
        ],
        subId: [
          {
            validator: (rule, value, callback) => {
              if (!this.formData1.subId) {
                callback(new Error("患者来源必须选择"));
              } else {
                callback();
              }
            },
            required: true,
            message: "必须选择患者来源",
            trigger: "change",
          },
        ],
        moduleName: [
          {
            required: true,
            message: "请输入模块名称",
            trigger: "blur",
          },
        ],
        moduleSort: [
          {
            required: true,
            message: "请输入显示顺序",
            trigger: ["blur", "change"],
          },
        ],
        remark: [],
      },
    };
  },
  //方法集合
  methods: {
    /** 随访对话框关闭 */
    detailClose() {
      this.detailVisible = false;
      this.detailModule = {};
      // 详情字段对象
      this.detailFileds = [];
    },
    /** 随访模块详情 */
    handleDetail(row) {
      const id = row.id;
      this.detailVisible = true;
      this.detailLoading = true;
      detailModuleById(id)
        .then((response) => {
          const data = response.data;
          this.detailFileds = data.params.fieldList;
          data.params = null;
          this.detailModule = data;
        })
        .catch(() => {})
        .finally(() => {
          this.detailLoading = false;
        });
    },
    /** 获取状态信息 */
    getStatusMsg(status) {
      if (status === 0) {
        return "未完成";
      } else if (status === 1) {
        return "已完成";
      }
    },
    /** 获取tag标签类型 */
    getTagType(status) {
      if (status === 0) {
        return "info";
      } else if (status === 1) {
        return "success";
      }
    },
    /** 第二步提交 */
    handleSubmit() {
      if (this.isSave) {
        const requestData = {
          filedList: this.visitFieldList,
        };
        this.step2Loading = true;
        this.buttonLoading = true;
        saveBatchField(requestData)
          .then((response) => {
            this.$modal.msgSuccess("添加成功");
            this.handleClose();
          })
          .catch(() => {})
          .finally(() => {
            this.step2Loading = false;
            this.buttonLoading = false;
          });
      }
    },
    /** 删除字段 */
    removeFieldHandle(fieldIndex) {
      if (this.isSave) {
        // 不保存数据库
        this.deleteField(fieldIndex);
      } else {
        this.removeField(fieldIndex);
      }
    },
    /** 添加字段 */
    addFiledHandle() {
      if (this.isSave) {
        // 不保存数据库
        this.saveField();
      } else {
        this.addField();
      }
    },
    /** 更新字段 */
    updateField() {
      let index = this.visitFieldValue;
      this.$refs["editForm"][index].validate((valid) => {
        if (!valid) return;
        this.tabLoading = true;
        const form = this.visitFieldList[index];
        form.moduleId = this.formData1.id;
        updateVisitField(form)
          .then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.editField();
          })
          .catch(() => {})
          .finally(() => {
            this.tabLoading = false;
          });
      });
    },
    addField() {
      this.formData2.moduleId = this.formData1.id;
      this.$refs["formData2"].validate((valid) => {
        if (!valid) return;
        this.step2Loading = true;
        saveVisitField(this.formData2)
          .then((response) => {
            this.$modal.msgSuccess("添加成功");
            const copiedObject = { ...this.formData2 };
            copiedObject.moduleId = this.formData1.id;
            copiedObject.id = response.data;
            this.visitFieldList.push(copiedObject);
            this.visitFieldValue = this.visitFieldList.length - 1 + "";
            this.resetForm("formData2");
          })
          .catch(() => {})
          .finally(() => {
            this.step2Loading = false;
          });
      });
    },
    /** 删除字段 */
    removeField(fieldIndex) {
      this.$modal
        .confirm('是否确认删除【随访字段】索引为"' + fieldIndex + '"的数据项？')
        .then(() => {
          this.tabLoading = true;
          const id = this.visitFieldList[fieldIndex].id;
          return removeVisitField(id);
        })
        .then(() => {
          this.deleteField(fieldIndex);
        })
        .catch(() => {})
        .finally(() => {
          this.tabLoading = false;
        });
    },
    /** 保存字段不访问数据库 */
    saveField() {
      this.$refs["formData2"].validate((valid) => {
        if (!valid) return;
        this.$modal.msgSuccess("添加成功");
        const copiedObject = { ...this.formData2 };
        copiedObject.moduleId = this.formData1.id;
        this.visitFieldList.push(copiedObject);
        this.visitFieldValue = this.visitFieldList.length - 1 + "";
        this.resetForm("formData2");
        this.formData2.id = null;
      });
    },
    /** 删除字段不访问数据库 */
    deleteField(removeIndex) {
      removeIndex = parseInt(removeIndex);
      this.visitFieldList.splice(removeIndex, 1);
      this.visitFieldValue = 0 + "";
      this.$modal.msgSuccess("删除成功");
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 获取患者来源
      this.editVisible = true;
      this.step1Loading = true;
      this.resetForm("formData1");
      this.resetForm("formData2");
      subTree().then((response) => {
        this.editTitle = "添加随访模块";
        this.subOptions = response.data;
        this.step1Loading = false;
        this.isSave = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id ? row.id : this.ids[0];
      this.editVisible = true;
      this.step1Loading = true;
      this.resetForm("formData1");
      this.resetForm("formData2");
      subTree().then((response) => {
        this.subOptions = response.data;
        infoVisitModule(id).then((response) => {
          const data = response.data;
          this.visitFieldList = data.params.fieldList;
          this.subIds = data.params.subIds;
          data.params = undefined;
          this.formData1 = data;
          this.editTitle = "修改随访模块";
          this.step1Loading = false;
          this.isSave = false;
        });
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listVisitModule(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.visitModuleList = response.data.list;
          this.total = response.data.totalCount;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      subTree().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 病情分类选择框改变 */
    querySubChange(value) {
      this.queryParams.subId = value[value.length - 1];
    },
    /** 病情分类选择框改变 */
    handleSubChange(value) {
      this.formData1.subId = value[value.length - 1];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.cascaders = [];
      this.handleQuery();
    },
    /** 初始化 */
    init() {
      this.getDeptTree();
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = [row.id] || this.ids;
      this.$modal
        .confirm('是否确认删除【随访模块】编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return removeVisitModule(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    handleClose() {
      this.visitFieldList = [];
      this.resetForm("formData1");
      this.active = 0;
      this.subIds = [];
      this.buttonLoading = false;
      this.step1Loading = false;
      this.step2Loading = false;
      this.editVisible = false;
      this.visitFieldValue = 0 + "";
      this.getList();
    },
    /** 模块信息提交 */
    submitForm() {
      this.$refs["formData1"].validate((valid) => {
        if (!valid) return;
        // TODO 提交表单
        this.buttonLoading = true;
        this.step1Loading = true;
        if (this.formData1.id) {
          // 更新
          updateVisitModule(this.formData1)
            .then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.active = 1;
            })
            .finally(() => {
              this.buttonLoading = false;
              this.step1Loading = false;
            });
        } else {
          // 保存
          saveVisitModule(this.formData1)
            .then((response) => {
              this.formData1.id = response.data;
              this.$modal.msgSuccess("添加成功");
              this.active = 1;
            })
            .finally(() => {
              this.buttonLoading = false;
              this.step1Loading = false;
            });
        }
      });
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.init();
  },
};
</script>
